package com.example.thirdhomework

import android.os.Bundle
import android.os.CountDownTimer
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class StopWatchActivity : AppCompatActivity() {

    private var isRunning = false
    private var seconds = 0
    private lateinit var timer: CountDownTimer
    private lateinit var timeTextView: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_stopwatch)

        timeTextView = findViewById(R.id.timeTextView)

        findViewById<Button>(R.id.startButton).setOnClickListener {
            if (!isRunning) {
                startTimer()
            }
        }

        findViewById<Button>(R.id.stopButton).setOnClickListener {
            if (isRunning) {
                stopTimer()
            }
        }
    }

    private fun startTimer() {
        isRunning = true
        timer = object : CountDownTimer(Long.MAX_VALUE, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                seconds++
                updateTimeText()
            }

            override fun onFinish() {}
        }.start()
    }

    private fun stopTimer() {
        isRunning = false
        timer.cancel()
    }

    private fun updateTimeText() {
        val minutes = seconds / 60
        val secondsLeft = seconds % 60
        timeTextView.text = String.format("%02d:%02d", minutes, secondsLeft)
    }
}
